package com.example.springboot_rabbitmq.direct;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author mayujie@jyd.com.cn
 * @version v1.0
 * @description MyCallBack
 * @date 2022/7/5 10:09
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;


    @PostConstruct  // 在Bean创建并完成赋值，执行初始化之前调用
    public void init() {
        // 注入到RabbitTemplate
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * correlationData 保存回调消息的ID及相关信息
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : null;
        if (ack) {
            log.info("交换机收到ID为：{}的消息！", id);
        } else {
            log.info("交换机还未收到ID为：{}的消息！", id);
        }
    }

}
